package org.zhq.controller.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.zhq.Const;
import org.zhq.ServerResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate redisTemplate;

    public UserTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        if (StrUtil.isNotBlank(userId) && StrUtil.isNotBlank(userToken)) {
            String token = redisTemplate.opsForValue().get(Const.Redis.USER_TOKEN + ":" + userId);
            if (StrUtil.isBlank(token)) {
                returnErrorResponse(response, ServerResult.errorMsg("用户未登录"));
                return false;
            } else {
                if (!StrUtil.equals(token, userToken)) {
                    returnErrorResponse(response, ServerResult.errorMsg("用户异地登录"));
                    return false;
                }
            }
        } else {
            returnErrorResponse(response, ServerResult.errorMsg("用户未登录"));
            return false;
        }
        return true;
    }

    private void returnErrorResponse(HttpServletResponse response, ServerResult result) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(JSONUtil.toJsonStr(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
